
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
  //render方法将变量写入模板模板引擎ejs中
});


//配置图片上传的路由
router.post('/uploadImg', function(req, res, next) {
  var form = new multiparty.Form();    
  //设置编码    
  form.encoding = 'utf-8';    
 
  //设置文件存储路径    
  form.uploadDir = './uploadtemp';    
 
  //设置文件大小限制   
  form.maxFilesSize = 2 * 1024 * 1024; 

  form.parse(req,function(err,fields,files){        
    var uploadurl = './images/upload/';        
    file = files['filedata'];

    //传递过来的文件名        
    originalFilename= file[0]. originalFilename; 

    //原始文件名        
    tmpPath = file[0].path;    
    //设置时间戳，用做文件名     
    var timestamp = new Date().get();
    console.log(timestamp)        
    uploadurl += timestamp + originalFilename;

    newPath = './public/' + uploadurl;        

    var fileReadStream = fs.createReadStream(tmpPath);   
    //从原始path路径中读出文件
    var fileWriteStream = fs.createWriteStream(newPath);
    //利用带有时间戳的地址储存文件        
    fileReadStream.pipe(fileWriteStream); //管道流 
    //将原来的文件写到目标文件中       
    fileWriteStream.on('close',function(){           
      fs.unlinkSync(tmpPath); 
      // console.log(tmpPath);           
      res.send('{"err":"","msg":"'+uploadurl+'"}'); 
      //编辑器的规定       
    });
  });
});
module.exports = router;
